/**
 * 日志管理器模块
 * 负责日志显示和管理
 */

class LogManager {
    constructor() {
        this.logsContainer = document.getElementById('logsContainer');
        this.init();
    }

    init() {
        this.loadRecentLogs();
    }

    addLogEntry(type, message) {
        if (!this.logsContainer) return;

        const timestamp = new Date().toLocaleString('zh-CN');
        const logEntry = document.createElement('div');
        logEntry.className = `log-entry log-${type}`;
        logEntry.textContent = `[${timestamp}] ${message}`;

        this.logsContainer.appendChild(logEntry);
        this.logsContainer.scrollTop = this.logsContainer.scrollHeight;

        // 限制日志数量
        while (this.logsContainer.children.length > 100) {
            this.logsContainer.removeChild(this.logsContainer.firstChild);
        }
    }

    async loadRecentLogs() {
        if (!this.logsContainer) return;

        try {
            const response = await fetch('/api/logs/recent');
            const logs = await response.json();

            // 清空现有日志
            this.logsContainer.innerHTML = '';

            logs.forEach(log => {
                const logEntry = document.createElement('div');
                logEntry.className = `log-entry log-${log.type}`;
                logEntry.textContent = log.content;
                this.logsContainer.appendChild(logEntry);
            });

            this.logsContainer.scrollTop = this.logsContainer.scrollHeight;
        } catch (error) {
            console.error('Failed to load logs:', error);
            this.addLogEntry('error', '加载日志失败');
        }
    }

    clearLogs() {
        if (this.logsContainer) {
            this.logsContainer.innerHTML = '';
        }
    }
}

// 导出到全局
window.LogManager = LogManager; 